/**
 * @Description: 三级城市：（一张表、统计局抓取的数据）
 * @author ourslookAdmin
 * @date 2019-05-09 17:09:14
 */
import React, { Fragment } from 'react';
import {
  Button,
  Card,
  Checkbox,
  Col,
  Divider,
  Form,
  Input,
  InputNumber,
  Radio,
  Row,
  Select,
  Spin,
  Tag,
  TreeSelect,
  Table,
  BackTop,
} from 'antd/lib/index';
import { formatMessage, FormattedMessage } from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import { getWebPath } from '../../../utils/request';
import uiUtils, { hasPermission, rulesReg, rulesRemote } from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import coming from '@/decorator/coming';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

// @coming({title: '精彩即将呈现！', value: Date.now() + 1000 * 60 * 60 * 24 * 2})
@connect(() => ({}))
class InfArea extends React.Component {
  params = {
    page: 1,
    limit: 40,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      // render: (value, record, index) => index + 1,
    },
    {
      title: '区域编码',
      dataIndex: 'areaCode',
      width: 150,
      align: 'center',
      sorter: true,
      key: 'area_code',
    },
    {
      title: '省份名称',
      dataIndex: 'areaName',
      align: 'center',
      sorter: false,
      key: 'area_name',
      render: (value, record) => {
        if (record.level === 1) {
          return record.areaName;
        }
        return '- -';
      },
    },
    {
      title: '城市名称',
      dataIndex: 'shiAreaName',
      width: 150,
      align: 'center',
      sorter: false,
      key: 'shi_area_name',
      render: (value, record) => {
        if (record.level === 2) {
          return record.areaName;
        }
        return '- -';
      },
    },
    {
      title: '区/县名称',
      dataIndex: 'quAreaName',
      width: 150,
      align: 'center',
      sorter: false,
      key: 'qu_area_name',
      render: (value, record) => {
        if (record.level === 3) {
          return record.areaName;
        }
        return '- -';
      },
    },
    {
      title: '层级',
      dataIndex: 'level',
      width: 150,
      align: 'center',
      sorter: false,
      key: 'level',
      render: value => {
        let level = '';
        if (value === 1) {
          level = '省份';
        } else if (value === 2) {
          level = '城市';
        } else if (value === 3) {
          level = '区/县';
        }
        return level;
      },
    },
    // { title: '排序', dataIndex: 'sort', width: 120, align: 'center', sorter: true, key: 'sort' },
    // {
    //   title: '状态',
    //   dataIndex: 'status',
    //   width: 30,
    //   align: 'center',
    //   fixed: 'right',
    //   render: (value, record, index) =>
    //     value === 0 ? (
    //       <Tag style={{ cursor: 'default' }} className={styles.label_success}>
    //         正常
    //       </Tag>
    //     ) : (
    //       <Tag style={{ cursor: 'default' }} className={styles.label_danger}>
    //         暂停
    //       </Tag>
    //     ),
    // },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: InfArea.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
    };
  }

  // 筛选条件
  static getFormList = () => [
    // {
    //   type: 'SELECT',
    //   field: 'level',
    //   placeholder: '层级',
    //   initialValue: '',
    //   list: [
    //     { id: '', name: '请选择层级' },
    //     { id: '1', name: '省份' },
    //     { id: '2', name: '城市' },
    //     { id: '3', name: '区/县' },
    //   ],
    // },
    {
      type: 'SELECT',
      field: 'areaCode',
      placeholder: '省份',
      initialValue: '',
      list: [{ id: '', name: '请选择省份' }],
    },

    //下面是各种组件的示例代码，不用 请删除不需要的代码和注释
  ];

  componentDidMount() {
    this.getAreaSelectList();
    this.requestList();
  }

  componentWillUnmount() {}

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: {},
      showList: 2,
    });
  };

  update = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />,
      editModel: JSON.parse(JSON.stringify(selectedRows[0])),
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  view = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}infarea/delete`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const infArea = Object.assign(this.state.editModel, this.editForm.props.form.getFieldsValue());

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url = infArea.id == null ? '/infarea/save' : '/infarea/update';
        //对象删除一个属性
        //delete infArea.xxxxPros;
        if (infArea.level === 2) {
          infArea.parentAreaCode = infArea.shengAreaCode;
        } else if (infArea.level === 3) {
          infArea.parentAreaCode = infArea.shiAreaCode;
        }
        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(getWebPath() + url, {
          method: 'POST',
          body: infArea,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!infArea.id) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getInfo = id => {};

  getAreaSelectList = () => {
    //获取所有的顶级菜单
    requestPromise(`${getWebPath('/infarea/areaList')}`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const menus = res.datas || [];
        const newMenus = [
          { id: '', name: '请选择省份' },
          ...menus.map(e => ({ id: e.areaCode, name: e.areaName })),
        ];

        const { formList: formListNew } = this.state;
        const formItem = this.findFormListItemByField('areaCode');
        formItem.list = newMenus;
        this.setState({
          formList: formListNew,
        });
      }
    });
  };

  updateData = () => {
    this.setState({
      loading: true,
    });
    //获取所有的顶级菜单
    requestPromise(`${getWebPath('/infarea/updateData')}`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        uiUtils.showAlert(`同步完成，共同步数据${res.data}条`);
        this.setState({
          loading: false,
        });
        this.requestList();
      }
    });
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  operateByIds = status => {
    //这里处理，发布、取消发布、删除、禁用等状态操作; 参数status由调用放传入
    // const {selectedRows, selectedIds, selectedIndexs} = this.state;
    // const ids = [];
    // for (let i = 0; i < selectedRows.length; i += 1) {
    //   ids.push(selectedRows[i].id);
    // }
    //
    // /* eslint-disable no-param-reassign */
    // status = !status ? 3 : status;
    // let tips = "请确定是否要进行操作??????";
    // let msgIds = null;
    // if (status === 2) {
    //   msgIds = 'ours.curd.show-alert.confirm-publish';//发布
    // } else if (status === 3) {
    //   msgIds = 'ours.curd.show-alert.confirm-delete';//删除
    // } else if (status === 1) {
    //   tips = "请选择要撤消选中项吗？";
    //   msgIds = 'ours.curd.show-alert.confirm-enable';//启用
    // } else if (status === -1) {
    //   msgIds = 'ours.curd.show-alert.confirm-disable';//禁用
    // }
    //
    // uiUtils.showConfirm(formatMessage({id: msgIds}), () => {
    //   this.setState({
    //     loading: true,
    //   });
    //   //const data = 'modelIds=' + ids.join(',') + '&status=' + status;
    //   const data = {
    //     modelIds: ids.join(','),
    //     status,
    //   };
    //   requestPromise(`${getWebPath()}infarea/operateInfAreaByIds`, {
    //     method: 'POST',
    //     contentType: "application/x-www-form-urlencoded",
    //     body: data,
    //   }).then(res => {
    //     this.setState({
    //       loading: false,
    //     });
    //     if (res && res.code === 0) {
    //       uiUtils.showMessage(
    //         formatMessage({id: 'ours.curd.show-alert.operate-success'}),
    //         'success'
    //       );
    //       this.requestList();
    //     }
    //   });
    // });
  };

  //========其他所有的处理方法，请在按照约定进行处理==========

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.setState({
      list: [],
    });
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath()}infarea/list`, this.params);
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('infarea:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增" />
            </Button>
            <Button
              type="primary"
              icon="edit"
              {...style}
              onClick={this.update}
              hidden={!hasPermission('infarea:update')}
            >
              <FormattedMessage id="ours.curd.list.update" defaultMessage="修改" />
            </Button>
            {/*<Button*/}
            {/*  type="primary"*/}
            {/*  icon="info-circle"*/}
            {/*  {...style}*/}
            {/*  onClick={this.view}*/}
            {/*  hidden={!hasPermission('infarea:info')}*/}
            {/*>*/}
            {/*  <FormattedMessage id="ours.curd.list.info" defaultMessage="查看"/>*/}
            {/*</Button>*/}
            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('infarea:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />
            </Button>
            <Button
              type="default"
              icon="info-circle"
              {...style}
              onClick={this.operateByIds(2)}
              hidden={!hasPermission('infarea:update')}
            >
              <FormattedMessage id="ours.curd.list.publish" defaultMessage="发布" />
            </Button>
            <Button
              type="default"
              icon="info-circle"
              {...style}
              onClick={this.operateByIds(1)}
              hidden={!hasPermission('infarea:update')}
            >
              <FormattedMessage id="ours.curd.list.enable" defaultMessage="启用" />
            </Button>
            <Button
              type="default"
              icon="info-circle"
              {...style}
              onClick={this.operateByIds(-1)}
              hidden={!hasPermission('infarea:update')}
            >
              <FormattedMessage id="ours.curd.list.disable" defaultMessage="禁用" />
            </Button>
            <Button
              type="primary"
              style={{
                marginLeft: 10,
                marginTop: 10,
              }}
              onClick={this.updateData}
              hidden={!hasPermission('infarea:updatedata')}
            >
              同步数据
            </Button>
          </Fragment>

          <div className="content-wrap" style={{ marginTop: 20 }}>
            {/*<ETable*/}
            {/*  onSelectRow={uiUtils.onSelectRow.bind(this)}*/}
            {/*  primaryKey="id"*/}
            {/*  rowSelection={null}*/}
            {/*  selectedRows={this.state.selectedRows}*/}
            {/*  selectedIds={this.state.selectedIds}*/}
            {/*  selectedIndexs={this.state.selectedIndexs}*/}
            {/*  onChange={this.filtersSorterChange}*/}
            {/*  columns={this.columns}*/}
            {/*  dataSource={this.state.list}*/}
            {/*  pagination={this.state.pagination}*/}
            {/*  loading={this.state.loading}*/}
            {/*  scroll={{ x: 900 }}*/}
            {/*/>*/}
            <Table
              columns={this.columns}
              dataSource={this.state.list}
              loading={this.state.loading}
              scroll={{ x: 900 }}
              pagination={{ pageSize: 5 }}
              size="middle"
              bordered
            />
          </div>
        </Card>

        <BackTop />

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
          this.state.showList === 1 ? null : (
            <Card
              title={this.state.editModalTitle}
              bordered={false}
              actions={[
                <div>
                  <React.Fragment>
                    <Button
                      type="primary"
                      hidden={this.state.editModalType === 'view'}
                      style={{ marginRight: '18px' }}
                      onClick={this.saveOrUpdate}
                    >
                      <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
                    </Button>
                    <Button
                      style={{ marginRight: '18px' }}
                      onClick={() => {
                        this.editForm.props.form.resetFields();
                        this.setState({ showList: 1 });
                      }}
                    >
                      <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                    </Button>
                  </React.Fragment>
                </div>,
              ]}
              style={{ ...this.vShow(2) }}
              bodyStyle={{ padding: '20px' }}
              ref={node => {
                this.container = node;
              }}
            >
              <EditForm
                type={this.state.editModalType}
                model={this.state.editModel}
                wrappedComponentRef={inst => {
                  this.editForm = inst;
                }}
              />
            </Card>
          )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default InfArea;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
  };

  constructor(props) {
    super(props);
    this.state = {};
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {
    if (nextProps.model) {
      // this.state = {};
      //使用setFieldsValue实现修改form value的值，不用使用 this.setState({});
      // this.props.model.xxx = 'value';
      // this.props.form.setFieldsValue({ xxx: 'value' });
    }
  }

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  getAreaSelectList = () => {
    requestPromise(`${getWebPath('/infarea/areaList')}`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const datas = [];
        res.datas.forEach(d => {
          datas.push(<Option value={d.areaCode}>{d.areaName}</Option>);
        });
        this.setState({
          shengDatas: datas,
        });
      }
    });
  };

  /**
   * 获取城市列表
   */
  getCityList = parentAreaCode => {
    requestPromise(`${getWebPath(`/infarea/areaList?level=2&parentAreaCode=${parentAreaCode}`)}`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const datas = [];
        res.datas.forEach(d => {
          datas.push(<Option key={d.areaCode}>{d.areaName}</Option>);
        });
        this.setState({
          shiDatas: datas,
        });
      }
    });
  };

  changeLevel = value => {
    if (value === 2 || value === 3) {
      this.getAreaSelectList();
    }
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const { shiDatas } = this.state;
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Form layout="horizontal">
        <Row gutter={{ ...rowGutterPxLayout }}>
          <Col {...colSpanLayout}>
            <FormItem label="层级" {...formItemLayout}>
              {type === 'view'
                ? model.level
                : getFieldDecorator('level', {
                    initialValue: '',
                    rules: [
                      {
                        required: true,
                        message: '请选择层级',
                      },
                    ],
                  })(
                    <Select
                      style={{ width: 330 }}
                      onChange={value => {
                        model.level = value;
                        this.changeLevel(value);
                      }}
                    >
                      <Option value="">请选择层级</Option>
                      <Option value={1}>省份</Option>
                      <Option value={2}>城市</Option>
                      <Option value={3}>区/县</Option>
                    </Select>
                  )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            {(model.level === 2 || model.level === 3) && (
              <FormItem label="省份" {...formItemLayout}>
                {getFieldDecorator('shengAreaCode', {
                  initialValue: '',
                  rules: [
                    {
                      required: true,
                      message: '请选择省份',
                    },
                  ],
                })(
                  <Select
                    style={{ width: 330 }}
                    placeholder="请选择省份"
                    optionFilterProp="children"
                    onChange={this.getCityList}
                    // onFocus={this.getAreaSelectList}
                    // onSearch={this.productSearch}
                    notFoundContent={null}
                  >
                    <Option value="">请选择省份</Option>
                    {this.state.shengDatas}
                  </Select>
                )}
              </FormItem>
            )}
          </Col>
          {model.level === 3 && (
            <Col {...colSpanLayout}>
              <FormItem label="城市" {...formItemLayout}>
                {type === 'view'
                  ? model.parentAreaId
                  : getFieldDecorator('shiAreaCode', {
                      initialValue: '',
                      rules: [
                        {
                          required: true,
                          message: '请选择城市',
                        },
                      ],
                    })(
                      <Select style={{ width: 330 }}>
                        <Option value="">请选择城市</Option>
                        {shiDatas}
                      </Select>
                    )}
              </FormItem>
            </Col>
          )}
          <Col {...colSpanLayout}>
            <FormItem label="区域编码" {...formItemLayout}>
              {type === 'view'
                ? model.areaCode
                : getFieldDecorator('areaCode', {
                    initialValue: model.areaCode,
                    rules: [
                      {
                        required: true,
                        message: '区域编码必填',
                      },
                      {
                        whitespace: true,
                        message: '不能包含空白符',
                      },
                      {
                        max: 20,
                        message: '最长20个字符',
                      },
                    ],
                  })(
                    <Input
                      type="text"
                      autocomplete="off"
                      {...inputCodeDisabled}
                      maxlength={20}
                      placeholder="区域编码"
                      style={{ width: 330 }}
                    />
                  )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="区域名称" {...formItemLayout}>
              {type === 'view'
                ? model.areaName
                : getFieldDecorator('areaName', {
                    initialValue: model.areaName,
                    rules: [
                      {
                        required: true,
                        message: '区域名称必填',
                      },
                      {
                        whitespace: true,
                        message: '不能包含空白符',
                      },
                      {
                        max: 20,
                        message: '最长20个字符',
                      },
                    ],
                  })(
                    <Input
                      type="text"
                      autocomplete="off"
                      {...inputCodeDisabled}
                      maxlength={20}
                      placeholder="区域名称"
                      style={{ width: 330 }}
                    />
                  )}
            </FormItem>
          </Col>
        </Row>
      </Form>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
